<template>
  <div class="app-container" style="height: calc(100vh - 84px);">
    <div v-show="!showKaoshi" style="width: 100%;height: 100%;overflow-y: auto;overflow-x: hidden;">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="所属课程" prop="courseId">
          <el-select v-model="queryParams.courseId" placeholder="请选择" clearable @change="handleChangeCoures">
            <el-option v-for="item in selectCourses" :key="item.courseId" :label="item.courseName"
              :value="item.courseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试班级" prop="classId">
          <el-select v-model="queryParams.classId" placeholder="请选择" clearable @focus="handleClassFocus">
            <el-option v-for="item in selectClasses" :key="item.classId" :label="item.className"
              :value="item.classId" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试状态" prop="examePro">
          <el-select v-model="queryParams.examePro" placeholder="请选择" clearable>
            <el-option v-for="item in scoreStatus" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['exam:exame:add']">新增</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <!-- 考试名称  课程名称 考试班级  试卷名称 试卷类型  考试时长 考试状态  考试开始时间 考试结束时间 发布状态 -->
      <el-table v-loading="loading" :data="exameList">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="考试名称" align="center" prop="exameTitle" />
        <el-table-column label="课程名称" align="center" prop="courseName" />
        <el-table-column label="考试班级" align="center" prop="className" />
        <el-table-column label="试卷名称" align="center" prop="paperName" />
        <el-table-column label="试卷类型" align="center" prop="exameTypeName" />
        <el-table-column label="考试时长" align="center" prop="paperTime" />
        <el-table-column label="考试状态" align="center" prop="exameStatusName" />
        <el-table-column label="考试开始时间" align="center" prop="exameStartTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.exameStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考试结束时间" align="center" prop="exameEndTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.exameEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考试发布状态" align="center" prop="examPublishStatusName" />
        <el-table-column label="参考人数" align="center" prop="exameCnt" />
        <el-table-column label="操作" align="center" width="140" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-show="scope.row.examPublishStatus === 2" link type="primary" icon="CirclePlus"
              @click="handleShowNotice(scope.row)" v-hasPermi="['exam:exame:join']">参加考试</el-button>
            <el-button v-show="scope.row.examPublishStatus === 1" link type="primary" icon="CollectionTag"
              @click="handlePublishExame(scope.row)" v-hasPermi="['exam:exame:publish']">发布</el-button>
            <el-button v-show="scope.row.examPublishStatus === 1" link type="primary" icon="Edit"
              @click="handleUpdate(scope.row)" v-hasPermi="['exam:exame:edit']">修改</el-button>
            <el-button v-show="scope.row.examPublishStatus === 1" link type="primary" icon="Delete"
              @click="handleDelete(scope.row)" v-hasPermi="['exam:exame:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>
    <startExame v-show="showKaoshi" :visible="showKaoshi" :exameId="currentExameId" :userInfo="userInfo"
      :ques="questions" :paperDetails="paperDetails" @paperSuccess="handlepaperSuccess" />
    <!-- 添加或修改考试大厅对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="exameRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="考试名称" prop="exameTitle">
          <el-input v-model="form.exameTitle" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select style="width: 100%;" v-model="form.courseId" placeholder="请选择" clearable
            @change="handleFormChangeCoures">
            <el-option v-for="item in selectCourses" :key="item.courseId" :label="item.courseName"
              :value="item.courseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试班级" prop="classId">
          <el-select style="width: 100%;" v-model="form.classId" placeholder="请选择" clearable
            @focus="handleFormClassFocus">
            <el-option v-for="item in formselectClasses" :key="item.classId" :label="item.className"
              :value="item.classId" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试试卷" prop="paperId">
          <el-select style="width: 100%;" v-model="form.paperId" placeholder="请选择" clearable
            @focus="handleFormPaperFocus">
            <el-option v-for="item in formselectPapers" :key="item.paperId" :label="item.paperName"
              :value="item.paperId" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试开始时间" prop="exameStartTime">
          <el-date-picker clearable v-model="form.exameStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择考试开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考试结束时间" prop="exameEndTime">
          <el-date-picker clearable v-model="form.exameEndTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择考试结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <noticeDialog v-model:visible="showNotice" :userInfo="userInfo" @finish="handleBeginKaoshi" />
  </div>
</template>

<script setup name="Exame">
import { listExame, getExame, delExame, addExame, updateExame, listPaper, pushCourseExame } from "@/api/exam/exame";
import { queryCourseList } from '@/api/analyse.js'
import {
  getPaper,
  getExameUserInfo
} from "@/api/exam/exame";
import { queryClassByCourseId } from "@/api/register/registerList.js";
import { scoreStatus } from '../../scoreManager/status'
import noticeDialog from "./noticeDialog";
import startExame from "./startExame";
import { ElMessage } from "element-plus"
import dayjs from 'dayjs';
const { proxy } = getCurrentInstance();
// 考试通知
const showNotice = ref(false)
const showKaoshi = ref(false)
const currentExameId = ref(null)
const currentPaperId = ref(null)
const userInfo = ref({})
const questions = ref([])
const paperDetails = ref({})
const handleShowNotice = (item) => {
  getExameUserInfo(item.exameId).then(response => {
    userInfo.value = response.data
    currentExameId.value = item.exameId
    currentPaperId.value = item.paperId
    showNotice.value = true
  }).catch(() => {
  });

}
const handlepaperSuccess = () => {
  showKaoshi.value = false
  getList();
}
const handleBeginKaoshi = () => {
  if (currentExameId.value) {
    proxy.$modal
      .confirm(
        "请确定是否开始考试？考试一旦开始将不能暂停，退出或切换界面考试将会自动交卷"
      )
      .then(function () {
        return getPaper(currentPaperId.value);
      })
      .then((response) => {

        const danxuanList = response.data.danxuanList
        danxuanList.forEach(i => { i.type = 1 })

        const duoxuanList = response.data.duoxuanList
        duoxuanList.forEach(i => { i.type = 2 })

        const panduanList = response.data.panduanList
        panduanList.forEach(i => { i.type = 3 })

        questions.value = [...danxuanList, ...duoxuanList, ...panduanList];
        console.log("🚀 ~ .then ~ questions.value:", questions.value)
        paperDetails.value = response.data
        showKaoshi.value = true
      })
      .catch((err) => {
        console.log(err);
        proxy.$modal.msgError(`试券获取失败，无该试券`);
      });
    return;
  }

  proxy.$modal.msgError(`试券获取失败，无该试券`);
}

// 筛选项
const selectClasses = ref([])
const selectCourses = ref([])
// 表单
const formselectClasses = ref([])
const formselectPapers = ref([])
// 
const exameList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseId: null,
    classId: null,
    examePro: null
  },
  rules: {
    exameTitle: [
      { required: true, message: "考试名称不能为空", trigger: "blur" }
    ],
    courseId: [
      { required: true, message: "所属课程不能为空", trigger: "change" }
    ],
    classId: [
      { required: true, message: "考试班级不能为空", trigger: "change" }
    ],
    paperId: [
      { required: true, message: "考试试卷不能为空", trigger: "change" }
    ],
    exameStartTime: [
      { required: true, message: "考试开始时间不能为空", trigger: "change" }
    ],
    exameEndTime: [
      { required: true, message: "考试结束时间不能为空", trigger: "change" }
    ]
  }
});
const { queryParams, form, rules } = toRefs(data);

/** 查询考试大厅列表 */
function getList() {
  loading.value = true;
  listExame(queryParams.value).then(response => {
    exameList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 获取下拉
const getSelectList = () => {
  queryCourseList().then(response => {
    if (response.code === 200) {
      selectCourses.value = response.rows
    }
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("exameRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置筛选条件按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 筛选条件 change事件
const handleChangeCoures = (item) => {
  console.log("🚀 ~ handleChangeCoures ~ item:", item)
  queryParams.value.classId = null
  selectClasses.value = []
  queryClassByCourseId({ courseId: queryParams.value.courseId }).then(response => {
    if (response.code === 200) {
      selectClasses.value = response.data
    }
  });
}
const handleClassFocus = () => {
  if (!queryParams.value.courseId || queryParams.value.courseId === '') {
    ElMessage.warning('请选择课程')
    return
  }
}
// 表单
const handleFormChangeCoures = (item) => {
  form.value.classId = null
  formselectClasses.value = []
  form.value.paperId = null
  formselectPapers.value = []
  queryClassByCourseId({ courseId: form.value.courseId }).then(response => {
    if (response.code === 200) {
      formselectClasses.value = response.data
    }
  });
  listPaper(form.value.courseId).then(response => {
    if (response.code === 200) {
      formselectPapers.value = response.rows
    }
  });
}
const handleFormClassFocus = () => {
  if (!form.value.courseId || form.value.courseId === '') {
    ElMessage.warning('请选择课程')
    return
  }
}
const handleFormPaperFocus = () => {
  if (!form.value.courseId || form.value.courseId === '') {
    ElMessage.warning('请选择课程')
    return
  }
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加考试大厅";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const res = await queryClassByCourseId({ courseId: row.courseId })
  if (res.code === 200) {
    formselectClasses.value = res.data
  }
  const res1 = await listPaper(row.courseId)
  if (res1.code === 200) {
    formselectPapers.value = res1.rows
  }

  form.value = {
    exameId: row.exameId,
    exameTitle: row.exameTitle,
    courseId: row.courseId,
    classId: row.classId,
    paperId: row.paperId,
    exameStartTime: row.exameStartTime,
    exameEndTime: row.exameEndTime
  };
  open.value = true;
  title.value = "修改考试大厅";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["exameRef"].validate(valid => {
    if (valid) {
      const time1 = dayjs(form.value.exameStartTime);
      const time2 = dayjs(form.value.exameEndTime);
      // 比较time1是否在time2之前
      if (!time1.isBefore(time2)) {
        ElMessage.warning('结束时间必须大于开始时间！')
        return
      }
      if (form.value.exameId != null) {
        updateExame(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addExame(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _exameIds = row.exameId || ids.value;
  proxy.$modal.confirm('是否确认删除该数据项？').then(function () {
    return delExame(_exameIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}
/** 发布按钮操作 */
function handlePublishExame(row) {
  const exameId = row.exameId;
  proxy.$modal.confirm('是否确认发布该数据？').then(function () {
    return pushCourseExame({ exameId });
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("发布成功");
  }).catch(() => { });
}

getSelectList()
getList();
</script>
